package com.realshare.frame.util.safety;

import com.realshare.frame.util.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * ${DESCRIPTION}
 *
 * @author realshare
 * @email 15075107780@139.com
 * @create 2018-09-18 上午 9:16
 * @modify 2018-09-18 上午 9:16
 **/
public class FileHandler {
    private static int BUFFER_SIZE = 8192;

    public static void handlerFile(String outPath, String inPath, Cipher cipher) {
        if (cipher != null) {
            CipherOutputStream fos = null;
            BufferedInputStream fis = null;
            try {
                byte[] readBuffer = new byte[BUFFER_SIZE];
                fos = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(outPath)), cipher);
                fis = new BufferedInputStream(new FileInputStream(FileUtils.createFile(inPath)));
                int size;
                while ((size = fis.read(readBuffer, 0, BUFFER_SIZE)) >= 0) {
                    fos.write(readBuffer, 0, size);
                }
                fos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                    }
                } catch (Exception ignored) {
                }
            }
        }
    }
}
